package com.youdianstar.app.ui.account

import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.lifecycle.Observer
import com.safframework.eventbus.EventBus
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.HttpCode
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.entity.BusEntity
import com.youdianstar.app.common.entity.UserInfo
import com.youdianstar.app.entity.UserCenterResponse
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver

import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.BR
import com.youdianstar.app.R
import com.youdianstar.app.databinding.ActivityChangeStep2Binding
import com.youdianstar.app.entity.AccountEdit
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.auko.startActivity
import com.youdianstar.app.common.auko.startActivityForResult
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: ChangeStep2Activity
 * Author: 82149 Create: 2023/7/24 11:45
 * Changes (from 2023/7/24)
 * --------------------------------------------------
 * description:修改账号  :邮箱/手机  ,步骤2 设置新账号
 * ---------------------------------------------------
 *
 */
class ChangeStep2Activity :BaseActivity<ActivityChangeStep2Binding,LoginViewModel>(){
    override fun layoutId(): Int = R.layout.activity_change_step2

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): LoginViewModel {
        val model: LoginViewModel by viewModel()
        return model
    }

    //是否直接绑定新账号 : 是-不显示步骤2UI
    private var isLinkNew = false
    private val REQUEST_CODE = 0x14
    private var countryCode: String? = null

    override fun initData() {
        super.initData()
        //Type : 0-Phone 1-Email
        val accountType = intent.getIntExtra(Extra.IT_TYPE, 0)
        isLinkNew = intent.getBooleanExtra(Extra.IT_Link,false)

        mViewModel.selectPhoneField.set(accountType == 0)
        mBinding.clTopStep.visibility = if (isLinkNew) View.GONE else View.VISIBLE
        mBinding.headBar.initTitle(this,
            if (isLinkNew){
                getString(if (accountType == 1) R.string.profile_addEmail else R.string.profile_addPhone)
            }else{
                getString(if (accountType == 1) R.string.profile_changeLoginEmail else R.string.profile_changePhoneNum)
            }
        )

        if (accountType == 1) {
            mBinding.tvStepContent.text = getString(R.string.profile_linkEmail)
        } else {
            mBinding.tvStepContent.text = getString(R.string.profile_linkPhoneNum)
        }

        if (accountType == 0) {
            val phoneCode: String = DataAppManager.instance.getPhoneCode()
            countryCode = if (StrUtil.isEmpty(countryCode))  "1"  else  phoneCode
            mBinding.tvPhoneCode.text = "+$countryCode"
            mViewModel.phoneDataField.set("")
        } else {
            mViewModel.emailDataField.set("")
        }
    }

    override fun initClickEvent() {
        mBinding.btnAction.setThrottleListener {
            val isSelectPhone = mViewModel.selectPhoneField.get() ?: true
            val phoneFiled = mViewModel.phoneDataField.get()
            val emailFiled = mViewModel.emailDataField.get()
            val otpPhoneFiled = mViewModel.otpPhoneField.get()
            val otpEmailFiled = mViewModel.otpEmailField.get()

            if (isSelectPhone && StrUtil.isEmpty(phoneFiled)) {
                toastShow(getString(R.string.toast_requiredPhone))
                return@setThrottleListener
            }
            if (isSelectPhone && !StrUtil.isEmpty(phoneFiled) && phoneFiled!!.length < 8) {
                toastShow(getString(R.string.toast_validPhone))
                return@setThrottleListener
            }

            if (!isSelectPhone && StrUtil.isEmpty(emailFiled)) {
                toastShow(getString(R.string.toast_requiredEmail))
                return@setThrottleListener
            }

            if (!isSelectPhone && !StrUtil.emailFormat(emailFiled)) {
                toastShow(getString(R.string.toast_validEmail))
                return@setThrottleListener
            }

            if (isSelectPhone) {
                if (StrUtil.isEmpty(otpPhoneFiled)){
                    toastShow(getString(R.string.toast_requiredCode))
                    return@setThrottleListener
                }
                if (otpPhoneFiled!!.length < 4){
                    toastShow(getString(R.string.toast_validCode))
                    return@setThrottleListener
                }
            }

            if (!isSelectPhone) {
                if (StrUtil.isEmpty(otpEmailFiled)){
                    toastShow(getString(R.string.toast_requiredCode))
                    return@setThrottleListener
                }
                if (otpEmailFiled!!.length < 4){
                    toastShow(getString(R.string.toast_validCode))
                    return@setThrottleListener
                }
            }
            showLoadingDialog("")
            //绑定新账号
            DataAppManager.instance.getUser()?.let { user ->
                val userEdt = if (isSelectPhone)
                    AccountEdit(id = user.id, code = countryCode!!.toInt(), phone = phoneFiled, msgCode = otpPhoneFiled)
                else
                    AccountEdit(id = user.id, email = emailFiled, msgCode = otpEmailFiled)

                mViewModel.edtAccount(userEdt)
            }
        }

        mBinding.tvPhoneCode.setThrottleListener {

            startActivityForResult<PhoneCodeActivity>(REQUEST_CODE)
        }

        mBinding.phoneSendOtp.setThrottleListener {
            //点击发送OTP判断
            val phoneFiled = mViewModel.phoneDataField.get()
            if (StrUtil.isEmpty(phoneFiled)) {
                toastShow(getString(R.string.toast_requiredPhone))
                return@setThrottleListener
            }
            if (!StrUtil.isEmpty(phoneFiled) && phoneFiled!!.length < 8) {
                toastShow(getString(R.string.toast_validPhone))
                return@setThrottleListener
            }
            showLoadingDialog("")
            mViewModel.getOTPCode(countryCode ?: "1", phoneFiled ?: "", "binding")
        }

        mBinding.emailSendOtp.setThrottleListener {
            //点击发送OTP判断
            val emailFiled = mViewModel.emailDataField.get()
            if (StrUtil.isEmpty(emailFiled)) {
                toastShow(getString(R.string.toast_requiredEmail))
                return@setThrottleListener
            }
            if (!StrUtil.emailFormat(emailFiled)) {
                toastShow(getString(R.string.toast_validEmail))
                return@setThrottleListener
            }
            showLoadingDialog("")
            // TODO: 邮箱OTP功能需要新的API接口支持
            // mViewModel.getOTPCode("", emailFiled, "email")
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.phoneCountEvent.observe(this, Observer {
            if (it == -1L) {
                mBinding.phoneSendOtp.isEnabled = true
                mBinding.phoneSendOtp.text = getString(R.string.login_get)
            } else {
                var time = "$it"
                if (time.length == 1) {
                    time = "0$it"
                }
                mBinding.phoneSendOtp.isEnabled = false
                mBinding.phoneSendOtp.text = time + "s"
            }
        })

        mViewModel.emailCountEvent.observe(this, Observer {
            if (it == -1L) {
                mBinding.emailSendOtp.isEnabled = true
                mBinding.emailSendOtp.text = getString(R.string.login_get)
            } else {
                var time = "$it"
                if (time.length == 1) {
                    time = "0$it"
                }
                mBinding.emailSendOtp.isEnabled = false
                mBinding.emailSendOtp.text = time + "s"
            }
        })

        mViewModel.otpPhoneResultData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                mViewModel.onPhoneOtpSuccess()
                mViewModel.downCountPhone()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                if (code == HttpCode.CODE_OTP_UNABLE || code == HttpCode.CODE_OTP_OVER) {
                    mBinding.phoneSendOtp.isClickable = false
                    mBinding.phoneSendOtp.setTextColor(getViewColor(this@ChangeStep2Activity,R.color.text_hint_input))
                }
            }
        })

        mViewModel.otpEmailResultData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                mViewModel.onEmailOtpSuccess()
                mViewModel.downCountEmail()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                if (code == HttpCode.CODE_OTP_UNABLE || code == HttpCode.CODE_OTP_OVER) {
                    mBinding.emailSendOtp.isClickable = false
                    mBinding.emailSendOtp.setTextColor(getViewColor(this@ChangeStep2Activity,R.color.text_hint_input))
                }
            }
        })

        mViewModel.editResultLiveData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                toastShow(getString(R.string.public_success))

                EventBus.post(BusEntity(DataCode.PUSH_UPDATE))
//                mViewModel.getAccount() 本页面更新方案
                Handler(Looper.myLooper()!!).postDelayed({
                    startActivity<ProfileActivity>()
                    finish()
                },1000L)
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        mViewModel.userCenterResultLiveData.observe(this, object : BaseApiResultObserver<UserCenterResponse>(false) {
            override fun onDataResult(data: UserCenterResponse?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let { userCenterResponse ->
                    // 将UserCenterInfo转换为UserInfo
                    val userInfo = UserInfo(
                        token = userCenterResponse.user.id.toString(),
                        id = userCenterResponse.user.id,
                        code = userCenterResponse.user.id,
                        phone = userCenterResponse.user.mobile,
                        email = userCenterResponse.user.email,
                        nickname = userCenterResponse.user.nickName,
                        realName = userCenterResponse.user.realName,
                        abb = null,
                        icon = userCenterResponse.user.avatar,
                        birthday = userCenterResponse.user.birthday,
                        sex = userCenterResponse.user.sex,
                        google = false,
                        receiptEmail = userCenterResponse.user.email,
                        deposit = userCenterResponse.user.securityFree,
                        inviteId = userCenterResponse.user.inviteUid.toString(),
                        inviteCode = "",
                        platformId = 1,
                        uid = userCenterResponse.user.id,
                        type = 1,
                        source = 1,
                        isNewUser = false,
                        isBranch = false
                    )
                    DataAppManager.instance.saveUser(userInfo)
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            countryCode = data?.getStringExtra(Extra.IT_CODE)
            mBinding.tvPhoneCode.text = "+$countryCode"
        }
    }


}